///////////////////////////////////////////////////////////////////////////////
//
//  Elfin
//  Kolonitsky Developers Alliance (c) 2012
//  All rights reserved
//
///////////////////////////////////////////////////////////////////////////////
package org.kolonitsky.alexey.net
{
    import flash.events.Event;
    import flash.events.EventDispatcher;
    import flash.events.TimerEvent;
    import flash.external.ExternalInterface;
    import flash.utils.Timer;

    import utils.Logger;

    [Event(name="change", type="flash.events.Event")]

    /**
     *
     */
    public class ReCaptchaService extends EventDispatcher
    {
        public static const IMAGE_URL:String = "http://www.google.com/recaptcha/api/image";

        [Bindable]
        public var challenge:String = "";

        [Bindable]
        public var imageURL:String ="";

        
        public function ReCaptchaService()
        {
            updateTimer = new Timer(1000, 20);
            updateTimer.addEventListener(TimerEvent.TIMER, updateTimerHandler);

            challenge = call("return RecaptchaState.challenge;");
            imageURL = IMAGE_URL + "?c=" + challenge;
            dispatchEvent(new Event(Event.CHANGE));
        }

        public function reload():void
        {
            Logger.log("INFO: ReCaptchaService reload ");
            call("Recaptcha.reload();");
            imageURL = "";
            updateTimer.start();
        }

        public function stop():void
        {
            updateTimer.stop();
        }

        public function start():void
        {
            updateTimer.start();
        }


        //---------------------------------------------------------------------
        //
        //  Private
        //
        //---------------------------------------------------------------------

        private var updateTimer:Timer = null;

        private function updateTimerHandler(event:TimerEvent):void
        {
            var c:String = call("return "
                + "document.getElementById('recaptcha_challenge_field').value;");

            if (c && c != challenge)
            {
                challenge = c;
                imageURL = IMAGE_URL + "?c=" + challenge;
                dispatchEvent(new Event(Event.CHANGE));
            }
        }
        
        private function call(code:String):String
        {
            var result:String = "";
            if (ExternalInterface.available)
                result = ExternalInterface.call("function () {" + code + "}");
            else
                Logger.log("WARNING: ReCaptureService: ExternalInterface unavailable");
            return result;
        }
    }
}
